﻿using MrdocUtils.Common;
using MrdocUtils.Model;
using Newtonsoft.Json;
using System.Text;

namespace MrdocUtils.Utils
{
    public class HttpHelper
    {
        public static T Post<T>(string url, HttpContent strData)
        {
            string result = string.Empty;
            HttpClient httpClient = new HttpClient();
            httpClient.Timeout = TimeSpan.FromMinutes(5);
            // 设置请求头信息
            httpClient.DefaultRequestHeaders.Add("Method", "Post");

            Task<HttpResponseMessage> postTask = httpClient.PostAsync(url, strData);
            postTask.Wait();
            if (postTask.IsCanceled)
            {
                throw postTask.Exception;
            }
            if (postTask.IsFaulted)
            {
                throw postTask.Exception;
            }
            HttpResponseMessage postResponse = postTask.Result;
            HttpResponseMessage rest = postResponse.EnsureSuccessStatusCode();

            if (rest.IsSuccessStatusCode)
            {
                result = postResponse.Content.ReadAsStringAsync().Result;
                var res = JsonConvert.DeserializeObject<ServiceAPIResult>(result);
                if (res.status)
                {
                    if (typeof(T) == typeof(bool))
                    {
                        return (T)(object)true;
                    }
                    return JsonConvert.DeserializeObject<T>(res.data.ToString());
                }
                else
                {
                    throw new Exception(res.data.ToString());
                }
            }
            else
            {
                throw new Exception(rest.StatusCode.ToString());
            }
        }
        public static string PostImg(string url, HttpContent strData)
        {
            string result = string.Empty;
            HttpClient httpClient = new HttpClient();
            httpClient.Timeout = TimeSpan.FromMinutes(5);
            // 设置请求头信息
            httpClient.DefaultRequestHeaders.Add("Method", "Post");

            Task<HttpResponseMessage> postTask = httpClient.PostAsync(url, strData);
            postTask.Wait();
            if (postTask.IsCanceled)
            {
                throw postTask.Exception;
            }
            if (postTask.IsFaulted)
            {
                throw postTask.Exception;
            }
            HttpResponseMessage postResponse = postTask.Result;
            HttpResponseMessage rest = postResponse.EnsureSuccessStatusCode();

            if (rest.IsSuccessStatusCode)
            {
                result = postResponse.Content.ReadAsStringAsync().Result;
                var res = JsonConvert.DeserializeObject<UploadImgResult>(result);
                if (res.success == 1)
                {
                    return res.url;
                }
                else
                {
                    throw new Exception(res.message.ToString());
                }
            }
            else
            {
                throw new Exception(rest.StatusCode.ToString());
            }
        }
        public static T Get<T>(string url, string authoriza = "")
        {
            string result = string.Empty;
            HttpClient httpClient = new HttpClient();

            httpClient.Timeout = TimeSpan.FromMinutes(2);
            // 设置请求头信息
            httpClient.DefaultRequestHeaders.Add("Method", "Get");
            if (authoriza != "")
            {
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authoriza);
            }
            var getTask = httpClient.GetAsync(url);
            if (getTask.IsCanceled)
                throw getTask.Exception;
            if (getTask.IsFaulted)
                throw getTask.Exception;
            HttpResponseMessage getResponse = getTask.Result;
            getResponse.EnsureSuccessStatusCode();
            result = getResponse.Content.ReadAsStringAsync().Result;
            var res = JsonConvert.DeserializeObject<ServiceAPIResult>(result);
            if (res.status)
            {
                return res.data != null ? JsonConvert.DeserializeObject<T>(res.data.ToString()) : default;
            }
            else
            {
                return default;
            }
        }

        #region Get
        /// <summary>
        /// 获取文集列表
        /// </summary>
        /// <returns></returns>
        public static List<ProjectsModel> GetProjects()
        {
            return Get<List<ProjectsModel>>(APINames.GetProjects);
        }

        /// <summary>
        /// 获取文集文档列表
        /// </summary>
        /// <param name="pid">文集ID</param>
        /// <param name="sort">排序方式，0为升序，1为降序，默认为0</param>
        /// <returns></returns>
        public static List<DocsModel> GetDocs(int pid, int sort = 0)
        {
            return Get<List<DocsModel>>(APINames.GetDocs + $"&pid={pid}&sort={sort}");
        }

        /// <summary>
        /// 获取个人文档列表
        /// </summary>
        /// <param name="page">文档列表页数</param>
        /// <param name="sort">排序方式，0为升序，1为降序，默认为0</param>
        /// <returns></returns>
        public static List<SelfDocModel> GetSelfDocs(int page, int sort = 0)
        {
            return Get<List<SelfDocModel>>(APINames.GetSelfDocs + $"&page={page}&sort={sort}");
        }
        /// <summary>
        /// 获取个人文档列表
        /// </summary>
        /// <param name="page">文档列表页数</param>
        /// <param name="sort">排序方式，0为升序，1为降序，默认为0</param>
        /// <param name="kw">文档搜索词，可选</param>
        /// <returns></returns>
        public static List<SelfDocModel> GetSelfDocs(int page, int sort, string kw)
        {
            return Get<List<SelfDocModel>>(APINames.GetSelfDocs + $"&page={page}&sort={sort}&kw={kw}");
        }

        /// <summary>
        /// 获取指定文档内容
        /// </summary>
        /// <param name="did"></param>
        /// <returns></returns>
        public static DocContentModel GetDoc(int did)
        {
            return Get<DocContentModel>(APINames.GetDoc + $"&did={did}");
        }

        #endregion

        #region Post
        /// <summary>
        /// 新建文集
        /// </summary>
        /// <param name="info"></param>
        /// <returns>返回创建好的文集ID</returns>
        public static int CreateProject(CreateProjectModel info)
        {
            string dataString = $"name={info.name}&desc={info.desc}";
            var strData = new StringContent(dataString, Encoding.UTF8, "application/x-www-form-urlencoded");
            var res = Post<int>(APINames.CreateProject, strData);
            return res;
        }

        /// <summary>
        /// 创建文档
        /// </summary>
        /// <param name="info"></param>
        /// <returns>返回创建好的文档ID</returns>
        public static int CreateDoc(CreateDocModel info)
        {
            var strData = new StringContent(info.ConvertToUrlPara(), Encoding.UTF8, "application/x-www-form-urlencoded");
            var res = Post<int>(APINames.CreateDoc, strData);
            return res;
        }

        /// <summary>
        /// 编辑文档
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static int ModifyDoc(ModifyDocModel info)
        {
            var strData = new StringContent(info.ConvertToUrlPara(), Encoding.UTF8, "application/x-www-form-urlencoded");
            var res = Post<int>(APINames.ModifyDoc, strData);
            return res;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param string="imgPath">图片的路径</param>
        /// <returns>返回上传后的图片链接</returns>
        public static string UploadImg(string imgPath)
        {
            string base64Str = $"data:image/jpeg;base64,{ImageUtil.ImgToBase64String(imgPath)}";
            var strData = new StringContent(base64Str, null, "text/plain");
            var res = PostImg(APINames.UploadImg, strData);
            return res;
        }
        #endregion
    }

    public static class APINames
    {
        /// <summary>
        /// 服务器地址
        /// </summary>
        public const string ServiceUrl = "http://127.0.0.1:10081";

        /// <summary>
        /// 用户的Token
        /// </summary>
        public const string Token = "50576b6a7827b7e2086f3c4de5c2c7ddbbe6bd26350a2d10636d716b";

        /// <summary>
        /// 获取文集列表
        /// </summary>
        public const string GetProjects = $"{ServiceUrl}/api/get_projects/?token={Token}";
        /// <summary>
        /// 获取文集文档列表
        /// </summary>
        public const string GetDocs = $"{ServiceUrl}/api/get_docs/?token={Token}";

        /// <summary>
        /// 获取个人创建的文档列表
        /// </summary>
        public const string GetSelfDocs = $"{ServiceUrl}/api/get_self_docs/?token={Token}";

        /// <summary>
        /// 获取指定文档内容
        /// </summary>
        public const string GetDoc = $"{ServiceUrl}/api/get_doc/?token={Token}";

        /// <summary>
        /// 新建文集
        /// </summary>
        public const string CreateProject = $"{ServiceUrl}/api/create_project/?token={Token}";

        /// <summary>
        /// 新建文档
        /// </summary>
        public const string CreateDoc = $"{ServiceUrl}/api/create_doc/?token={Token}";

        /// <summary>
        /// 更新文档
        /// </summary>
        public const string ModifyDoc = $"{ServiceUrl}/api/modify_doc/?token={Token}";

        /// <summary>
        /// 上传图片
        /// </summary>
        public const string UploadImg = $"{ServiceUrl}/api/upload_img/?token={Token}";
    }
}